package com.xiaochong.tir.manager.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaochong.tir.common.data.mapper.CurrencyInfoMapper;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.vo.CurrencyInfoIndexVo;
import com.xiaochong.tir.common.data.vo.KLineBroaderIndexVo;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.manager.component.HbaseBaseQueryComponent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.xiaochong.tir.common.data.po.KLineBroaderIndex;
import com.xiaochong.tir.common.data.mapper.KLineBroaderIndexMapper;

/**
 * 此类为[基础代码]自动生成,已经拥有基本的增删改成操作 
 * <其他请自行扩展>
 * @author cx
 * @time 2018-08-07 18:49
 * 
 */
@Service
public class KLineBroaderIndexService{
 
      
    @Autowired
	private KLineBroaderIndexMapper kLineBroaderIndexDao;
    @Autowired
    private CurrencyInfoMapper currencyInfoDao;
    @Autowired
    HbaseBaseQueryComponent hbaseBaseQueryComponent;
	
	/**
     * 新增
     * @param entity 
     * @param session
     */
    public int insertSelective (KLineBroaderIndex entity) { 
     return this.kLineBroaderIndexDao.insertSelective(entity);
    }	
    
    /**
     * 批量新增
     * @param list 
     * @param session
     */
    public void insertBatch(List<KLineBroaderIndex> list) {
           
          this.kLineBroaderIndexDao.insertBatch(list);
         
         
    }
    
    /**
     * 根据主键修改单条数据
     * @param entity 
     * @param session
     */
    public int updateByPrimaryKey(KLineBroaderIndex entity) {
           return this.kLineBroaderIndexDao.updateByPrimaryKey(entity);
    }
    
    /**
     * 根据主键批量修改数据
     * @param list 
     * @param session
     */
    public void updateBatch(List<KLineBroaderIndex> list) {
           
          this.kLineBroaderIndexDao.updateBatch(list);
          
        
    }
    
    /**
     * 根据主键查询单条数据
     * @param id
     */
    public KLineBroaderIndex selectByPrimaryKey(Integer id) {
            return this.kLineBroaderIndexDao.selectByPrimaryKey(id);
    }
    
    /**
     * 根据条件查询单条记录
     * @param entity 
     */
    public KLineBroaderIndex selectByEntity(KLineBroaderIndex entity) {
           return this.kLineBroaderIndexDao.selectByEntity(entity);
    }
    
    
    /**
     * 根据条件查询多条记录
     * @param entity 
     */
    public List<KLineBroaderIndex> selectByEntityList(KLineBroaderIndex entity) {
           return  this.kLineBroaderIndexDao.selectByEntityList(entity);
    }
    
    /**
     * 根据条件查询Id
     * @param entity 
     */
    public Integer selectById(KLineBroaderIndex entity) {
           return  this.kLineBroaderIndexDao.selectById(entity);
    }
    
     /**
     * 根据条件查询Ids
     * @param entity 
     */
    public List<Integer> selectByIds(KLineBroaderIndex entity) {
        return  this.kLineBroaderIndexDao.selectByIds(entity);
    }
    
     /**
     * 根据主键删除单条记录
     * @param id
     */
    public void deleteByPrimaryKey(Integer id) {
           this.kLineBroaderIndexDao.deleteByPrimaryKey(id);
    }
    
    /**
     * 根据主键删除多条记录
     * @param list
     */
    public void deleteBatch(List<Integer> list) {
           this.kLineBroaderIndexDao.deleteBatch(list);
    }
    
     /**
     * 根据某些条件删除
     * @param entity
     */
    public void deleteBatch(KLineBroaderIndex entity) {
           this.kLineBroaderIndexDao.deleteByEntity(entity);
    }

    //组装每日大盘指数
    public KLineBroaderIndexVo getBroaderIndex() {
        KLineBroaderIndexVo indexVo = new KLineBroaderIndexVo();
        KLineBroaderIndex index = new KLineBroaderIndex();
        //昨天大盘指数
        index.setDate(LocalDate.now().minusDays(1).format(DateUtils.format_ymds));
        KLineBroaderIndex Index0 = this.kLineBroaderIndexDao.selectByEntity(index);
        //前天大盘指数
        index.setDate(LocalDate.now().minusDays(2).format(DateUtils.format_ymds));
        KLineBroaderIndex Index1 = this.kLineBroaderIndexDao.selectByEntity(index);
        indexVo.setDate(LocalDate.now().minusDays(1).format(DateUtils.format_ymds));
        if( null!= Index0){
            indexVo.setOpenPrice(Index0.getOpenPrice());
            indexVo.setHighestPrice(Index0.getHighestPrice());
            indexVo.setLowestPrice(Index0.getLowestPrice());
            indexVo.setClosePrice(Index0.getClosePrice());
            //计算变动率
            if(null != Index1){
                if(StringUtils.isNotBlank(Index0.getClosePrice())&&StringUtils.isNotBlank(Index1.getClosePrice())){
                    BigDecimal big0 = new BigDecimal(Index0.getClosePrice());
                    BigDecimal big1 = new BigDecimal(Index1.getClosePrice());
                    if(!big1.equals(BigDecimal.ZERO)){
                        String change = String.valueOf(big0.subtract(big1).divide(big1,2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                        indexVo.setRateChange(change+"%");
                    }else{
                        indexVo.setRateChange("0%");
                    }
                }
            }else{
                indexVo.setRateChange("0%");
            }
        }

        // 查询所有货币
        List<CurrencyInfo> list = currencyInfoDao.selectAllEnableCurrencyList();
        try {
            if(!list.isEmpty()){
                BigDecimal volume = BigDecimal.ZERO;
                for (int i = 0; i < list.size(); i++) {
                    CurrencyInfo info = list.get(i);
                    if(StringUtils.isNotBlank(info.getCmcId())){
                        String rowKey = info.getCmcId() + "@" + DateUtils.getNextDayDateYMD(-1);
                        String grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                                , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                                , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                                , rowKey
                        );
                        if(StringUtils.isNotBlank(grailStr)){
                            JSONObject json = JSON.parseObject( grailStr );
                            if (json != null) {
                                Set<String> setString=json.keySet();
                                int lastKey=0;
                                for (String str : setString) {
                                    int maxStr=Integer.valueOf( str );
                                    if (maxStr>lastKey){
                                        lastKey = maxStr;
                                    }
                                }
                                //取出每个货币每天最后的成交额
                                JSONArray advice  = (JSONArray) json.getJSONArray( lastKey+"" );
                                if(null != advice){
                                    JSONObject obj=advice.getJSONObject( advice.size()-1 );
                                    if(obj.containsKey("volume24hCny")){
                                        BigDecimal decimal =new BigDecimal(String.valueOf(obj.get("volume24hCny")));
                                        volume = volume.add(decimal);//总成交额
                                    }
                                }
                            }
                        }
                    }
                }
                indexVo.setVolumeCapCny(String.valueOf(volume));
            }
        } catch (HbaseCloseExcetion hbaseCloseExcetion) {
            hbaseCloseExcetion.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (HbaseGetTableExcetion hbaseGetTableExcetion) {
            hbaseGetTableExcetion.printStackTrace();
        } catch (HbaseConnectionExcetion hbaseConnectionExcetion) {
            hbaseConnectionExcetion.printStackTrace();
        }
        return indexVo;
    }

    //组装货币指数
    public List<CurrencyInfoIndexVo> getCurrencyIndexList() {
        List<CurrencyInfo> list = this.currencyInfoDao.selectAllEnableCurrencyList();
        List<CurrencyInfoIndexVo> indexVos = new ArrayList<>();
        try{
            if(!list.isEmpty()){
                for (int i = 0; i < list.size(); i++) {
                    CurrencyInfo info = list.get(i);
                    if(StringUtils.isNotBlank(info.getCmcId())){
                        String rowKey = info.getCmcId() + DateUtils.getNextDayDateYMD(-1);
                        Map<String,Object> map = hbaseBaseQueryComponent.selectData(HbaseTableUtils.CURRENCY_INFO_K_LINE_TABLE_NAME ,rowKey);
                        if(!map.isEmpty()){
                            CurrencyInfoIndexVo vo1 = new CurrencyInfoIndexVo();
                            if(map.containsKey("openPrice")&& StringUtils.isNotBlank(String.valueOf(map.get("openPrice")))){
                                vo1.setOpenPrice(String.valueOf(map.get("openPrice")));
                            }else {
                                vo1.setOpenPrice("0");
                            }
                            if(map.containsKey("highestPrice")&& StringUtils.isNotBlank(String.valueOf(map.get("highestPrice")))){
                                vo1.setHighestPrice(String.valueOf(map.get("highestPrice")));
                            }else {
                                vo1.setHighestPrice("0");
                            }
                            if(map.containsKey("lowestPrice")&& StringUtils.isNotBlank(String.valueOf(map.get("lowestPrice")))){
                                vo1.setLowestPrice(String.valueOf(map.get("lowestPrice")));
                            }else {
                                vo1.setLowestPrice("0");
                            }
                            if(map.containsKey("closePrice")&& StringUtils.isNotBlank(String.valueOf(map.get("closePrice")))){
                                vo1.setClosePrice(String.valueOf(map.get("closePrice")));
                            }else {
                                vo1.setClosePrice("0");
                            }
                            vo1.setCoinName(info.getCoinNameCn()+"/"+info.getCoinNameEn());
                            if(map.containsKey("volume")&& StringUtils.isNotBlank(String.valueOf(map.get("volume")))){
                                vo1.setTurnover(String.valueOf(map.get("volume")));
                            }else {
                                vo1.setTurnover("0");
                            }
                            rowKey = info.getCmcId() + DateUtils.getNextDayDateYMD(-2);
                            map = hbaseBaseQueryComponent.selectData(HbaseTableUtils.CURRENCY_INFO_K_LINE_TABLE_NAME ,rowKey);
                            if(!map.isEmpty()){
                                BigDecimal tod = new BigDecimal(vo1.getClosePrice());
                                if(map.containsKey("closePrice")&& StringUtils.isNotBlank(String.valueOf(map.get("closePrice")))){
                                    BigDecimal yesd = new BigDecimal(String.valueOf(map.get("closePrice")));
                                    if(!yesd.equals(BigDecimal.ZERO)){
                                        vo1.setRateChange(String.valueOf(tod.subtract(yesd).divide(yesd, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)))+"%");
                                    }
                                }else {
                                    vo1.setRateChange("0%");
                                }
                            }else{
                                vo1.setRateChange("0%");
                            }
                            vo1.setDate(DateUtils.getNextDayDateYMD(-1));
                            indexVos.add(vo1);
                        }
                    }
                }
            }
        }catch (HbaseCloseExcetion hbaseCloseExcetion){
            hbaseCloseExcetion.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (HbaseGetTableExcetion hbaseGetTableExcetion) {
            hbaseGetTableExcetion.printStackTrace();
        } catch (HbaseConnectionExcetion hbaseConnectionExcetion) {
            hbaseConnectionExcetion.printStackTrace();
        }
        return indexVos;
    }
}